<?php
namespace Mp\Service\Widget;
use Illuminate\Contracts\Support\Renderable;
use Mp\Service\Common\Asset;

class Select2 extends Input{

	protected $symbol ;

	protected $name = 'select';

	protected $source = [];

	protected $single = false;   //单选

	protected $view = 'Mp::widgets.select2';

	const BEFORE = 'before';

	const BEHIND = 'behind';

	protected $css = [
		'static/mp/assets/plugins/select2/dist/css/select2.min.css',
		'static/mp/assets/plugins/select2/css/s2-docs.css',
	];

	protected $js = [
		'static/mp/assets/plugins/select2/dist/js/select2.full.min.js',
	];

	protected $script ; 

	protected function _init($params){
		Asset::css($this->css);
		Asset::js($this->js);
		
		$this->symbol = 'select2-'.str_random();
		$this->script = <<<SCRIPT

	$(".{$this->symbol}").select2();

SCRIPT;
	Asset::script($this->script);

		$this->data = [
			'name' => $this->name,
			'source' => $this->source,
			'symbol' => $this->symbol,
			'single' => $this->single,
		];
	}

	public function render($params = []){

		return parent::render();
	}

	public function option($params = [],$type = 'before'){
		$option = [
			'value' => $params['value'],
			'selected' => false,
			'label' => $params['label'] ?? 'option',
		];
		//追加
		if($type == self::BEHIND){
			array_push($this->source , $option);
		}elseif($type ==  self::BEFORE){
			//插入前面
			array_unshift($this->source , $option);
		}
		
		$this->data['source'] = $this->source;
		return $this;
	}

	public function selected($values = []){

		foreach($this->data['source'] as &$val){
			if(in_array($val['value'], (array)$values)){
				$val['selected'] = true;
			}
		}
		return $this;
	}
}